package controllers;

import helpers.UrlHelper;

import java.io.IOException;
import java.net.URLDecoder;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import entities.Domain;

import models.DomainModel;

public class BlacklistDomainServlet extends HttpServlet {
	public void doGet(HttpServletRequest request, HttpServletResponse response)
		throws IOException, ServletException {
		
		String path = ((HttpServletRequest) request).getRequestURI();
		String name = URLDecoder.decode(path.replaceAll(request.getServletPath() + "/", ""),"UTF-8");
		
		//Set message error
		if (name == null || name.isEmpty() || !UrlHelper.checkDomain(name)) {
			response.getWriter().println(name + " is not a valid domain.");
			return;
		}
		
		DomainModel domainModel = DomainModel.getInstance();
		Domain domain = domainModel.get(name);
		if (domain == null) {
			domain = new Domain();
			domain.setDomain(name);
			domain.setStatus(-1);
		} else if (domain.getStatus() == -1)  { 
			response.getWriter().println("domain " + name + " has been exists in blacklist.");
			return;
		} else {
			domain.setStatus(-1);
		}
		
		domainModel.insert(domain);
		
		response.getWriter().println("Add success domain " + name + " to blacklist");
		return;
	}
}
